package com.entor.interceptor;

import com.entor.util.JWTUtils;
import com.entor.util.Result;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if(token==null||token.equals("")){
            throw new Exception("用户未登录");
        }
        Result result = JWTUtils.checkToken(token);
        //认证不通过
        if(result.getCode()!=0){
            throw new Exception(result.getMsg());
        }
        //获取token的用户信息
        Map<String,Object> data = (Map<String, Object>) result.getData();
        String  username = (String) data.get("username");

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
